package com.example.myword;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import com.example.myword.dao.Word;
import com.example.myword.dao.WordDao;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class QuizActivity extends AppCompatActivity {
    private AppDatabase db;
    private WordDao wordDao;
    private List<Word> wordList;
    private TextView textViewQuizWord;
    private RadioGroup radioGroupOptions;
    private Button buttonSubmit;
    private String userId = "current_user_id";
    private String myId = userId;
    private Word currentWord;
    private String[] options = new String[4];
    private int correctOption;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        myId = getIntent().getStringExtra("userId");

        db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "word-database").allowMainThreadQueries().build();
        wordDao = db.wordDao();

        wordList = wordDao.getAllWords(userId);
        //更新单词库
        updateDemo();

        textViewQuizWord = findViewById(R.id.textViewQuizWord);
        radioGroupOptions = findViewById(R.id.radioGroupOptions);
        buttonSubmit = findViewById(R.id.buttonSubmit);


        loadNextQuestion();

        // 在按钮点击事件中添加动画效果
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 假设有个方法来处理答题逻辑
                checkAnswer();

                // 添加简单的放大动画
                v.animate()
                        .scaleX(1.2f)
                        .scaleY(1.2f)
                        .setDuration(300)
                        .withEndAction(new Runnable() {
                            @Override
                            public void run() {
                                v.animate()
                                        .scaleX(1.0f)
                                        .scaleY(1.0f)
                                        .setDuration(300)
                                        .start();
                            }
                        })
                        .start();
            }
        });


    }


    private void loadNextQuestion() {
        Random random = new Random();
        currentWord = wordList.get(random.nextInt(wordList.size()));
        textViewQuizWord.setText(currentWord.word);

        correctOption = random.nextInt(4);
        options[correctOption] = currentWord.meaning;

        // 单词语音播放
        Intent intent = new Intent(QuizActivity.this, AudioService.class);
        intent.putExtra("query", currentWord.word);
        startService(intent);
        // 随机生成其他错误选项
        Set<String> selectedOptions = new HashSet<>(); // 用于存储已经选过的单词含义
        selectedOptions.add(currentWord.meaning); // 将正确选项加入集合
        for (int i = 0; i < 4; i++) {
            if (i != correctOption) { // 跳过正确的选项位置
                int randomIndex;
                String option;
                do {
                    randomIndex = random.nextInt(wordList.size());
                    option = wordList.get(randomIndex).meaning;
                } while (selectedOptions.contains(option)); // 如果选过的单词含义与当前选项重复，则重新选择
                selectedOptions.add(option); // 将选过的单词含义加入集合
                options[i] = option; // 将选项设置为选中的单词含义
            }
        }

        for (int i = 0; i < 4; i++) {
            ((RadioButton) radioGroupOptions.getChildAt(i)).setText(options[i]);
        }
    }

    private void checkAnswer() {
        int selectedOption = radioGroupOptions.indexOfChild(findViewById(radioGroupOptions.getCheckedRadioButtonId()));
        if (selectedOption == correctOption) {
            Toast.makeText(this, "答对了!", Toast.LENGTH_SHORT).show();
        } else {
            //添加自己的错题本
            addToMyWord(currentWord.word, options[correctOption]);
            Toast.makeText(this, "答错了. 正确答案是: " + options[correctOption], Toast.LENGTH_SHORT).show();
        }

        loadNextQuestion();
    }

    public void addToMyWord(String word, String meaning) {
        // 检查数据库中是否已存在该单词
        Word existingWord = wordDao.getWord(myId, word);

        if (existingWord != null) {
            // 如果单词已存在，则更新wrongcount字段
            existingWord.wrongCount += 1; // 或者根据需要更新其他字段
            wordDao.update(existingWord);
        } else {
            // 创建一个新的Word对象，用获取到的文本内容填充其属性
            Word newWord = new Word();
            newWord.userId = myId;
            newWord.word = word;
            newWord.meaning = meaning;
            newWord.known = false;
            newWord.wrongCount = 1; // 初始wrongcount为1
            // 将新的单词插入到数据库中
            wordDao.insert(newWord);
            // 将新单词添加到一个列表中（通常是用于显示单词的列表）
            wordList.add(newWord);
        }
    }


    public void updateDemo() {
        List<Word> words = new ArrayList<>();
        words.add(new Word(userId, "hello", "你好", false));
        words.add(new Word(userId, "world", "世界", false));
        words.add(new Word(userId, "apple", "苹果", false));
        words.add(new Word(userId, "banana", "香蕉", false));
        for (Word word : words) {
            wordDao.insert(word);
        }
    }


}
